package com.starbucks.opencase.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.starbucks.opencase.enums.enumCMKey;
import com.starbucks.opencase.enums.enumCMMark;
import com.starbucks.opencase.enums.enumCMTip;
import com.starbucks.opencase.function.funCarry;
import com.starbucks.opencase.function.funSession;
import com.starbucks.opencase.tool.toolUserWallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class serUserWallet {
    @Autowired
    private funSession funSession;
    @Autowired
    private funCarry funCarry;
    @Autowired
    private toolUserWallet toolUserWallet;
    public void expendEnergy(String id, JsonNode message){
        ObjectMapper om=new ObjectMapper();
        ObjectNode on=om.createObjectNode();
        on.put(enumCMKey.mark.name(), enumCMMark.expendEnergy.ordinal());
        on.put(enumCMKey.timestamp.name(), System.currentTimeMillis());
        on.put(enumCMKey.status.name(), false);
        if(!funSession.isOnlineOfId(id,on))return;
        if(!message.has(enumCMKey.energy.name())){
            on.put(enumCMKey.tip.name(), enumCMTip.no_has_energy.getTip());
            funSession.sendMessage(id,on);
            return;
        }
        long energy=message.get(enumCMKey.energy.name()).asLong();
        if(energy<=0){
            on.put(enumCMKey.tip.name(), enumCMTip.error_expend_energy.getTip());
            funSession.sendMessage(id,on);
            return;
        }
        String uid= funSession.getUIdOfId(id);
        long now_energy= toolUserWallet.queryEnergy(uid);
        if(now_energy-energy<0){
            on.put(enumCMKey.tip.name(), enumCMTip.not_enough_energy.getTip());
            funSession.sendMessage(id,on);
            return;
        }
        toolUserWallet.subEnergy(uid,energy);
        on.put(enumCMKey.energy.name(), now_energy-energy);
        on.put(enumCMKey.status.name(), true);
        on.put(enumCMKey.expendEnergy.name(), energy);
        funSession.sendMessage(id,on);
    }
}
